package com.gxuwz.prrs.utils;

import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import com.gxuwz.prrs.BuildConfig;
import com.gxuwz.prrs.service.ServiceHolder;
import com.gxuwz.prrs.service.impl.UpdateServiceImpl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @author 张钧
 * @Description
 * @create 2023-05-25 下午 10:43
 */
public class UpdateUtils {
	public static void update(String version, AppCompatActivity activity) {
		UpdateServiceImpl updateService = ServiceHolder.getInstance().getBean(UpdateServiceImpl.class);
		String serverVersion = updateService.getVersion();
		if (!version.equals(serverVersion)) {
			AlertDialog.Builder builder = new AlertDialog.Builder(activity);
			builder.setTitle("检测到新版本");
			builder.setMessage("版本介绍:\n" + serverVersion);
			builder.setPositiveButton("以后再说", (dialog, which) -> {
					})
					.setNegativeButton("立即更新", (dialog, which) -> {
						AlertDialog.Builder updateBuilder = new AlertDialog.Builder(activity);
						updateBuilder.setTitle("下载中");
						updateBuilder.setNegativeButton("取消", (dialog1, which1) -> {
							dialog1.dismiss();
						});
						AlertDialog show = updateBuilder.show();
						try {
							downloadAPK(serverVersion,activity);
						} catch (Exception e) {
							throw new RuntimeException(e);
						}
						installAPK(serverVersion,activity);
						show.dismiss();
					});
			builder.show();
		} else {
			Toast.makeText(activity, "当前版本" + version + "已是最新版本", Toast.LENGTH_SHORT).show();
		}
	}

	private static void installAPK(String version, AppCompatActivity activity) {
		String sdPath = activity.getExternalCacheDir() + "/";
		String savePath = sdPath + "prrsdownload";
		File apkFile = new File(savePath, version+".apk");
		if (!apkFile.exists()) {
			return;
		}
		Intent intent = new Intent(Intent.ACTION_VIEW);
		//判断是否是AndroidN以及更高的版本
		intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		Uri contentUri = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".fileProvider", apkFile);
		intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
		activity.startActivity(intent);
	}

	private static void downloadAPK(String version,AppCompatActivity activity) throws IOException, ExecutionException, InterruptedException {
		CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
			if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
				try {
					String sdPath = activity.getExternalCacheDir()+ "/";
					String savePath = sdPath + "prrsdownload";
					File dir = new File(sdPath,"prrsdownload");
					if (!dir.exists()) {
						dir.mkdir();
					}
					HttpURLConnection conn = (HttpURLConnection) new URL("http://10.0.2.2:8080/download").openConnection();
					conn.connect();
					InputStream is = conn.getInputStream();
					File apkFile = new File(savePath,version+".apk");
					FileOutputStream fos = new FileOutputStream(apkFile);
					byte[] buffer = new byte[1024];
					while (true) {
						int numread = is.read(buffer);
						if (numread < 0) {
							break;
						}
						fos.write(buffer, 0, numread);
					}
					fos.close();
					is.close();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
		});
		voidCompletableFuture.get();
		CompletableFuture.allOf(voidCompletableFuture);
	}
}
